package cn.tonyandmoney.baidu.tts

import android.content.Context
import cn.tonyandmoney.baidu.bus.SpeechBus
import cn.tonyandmoney.baidu.tts.control.TtsInit
import cn.tonyandmoney.baidu.tts.event.SpeakEvent
import cn.tonyandmoney.baidu.tts.event.SynthesizeListener
import com.baidu.tts.client.SpeechError
import com.baidu.tts.client.SpeechSynthesizeBag
import com.baidu.tts.client.SpeechSynthesizer
import com.baidu.tts.client.SpeechSynthesizerListener
import org.jetbrains.anko.AnkoLogger

/**
 * Created by niantuo on 2018/2/28.
 * 百度语音合成
 */
class Speaker : SpeechSynthesizerListener, AnkoLogger {

    private var mSpeechSynthesizer = SpeechSynthesizer.getInstance()

    private val syntheMap = mutableMapOf<String, SynthesizeListener>()


    fun init(context: Context) {
        val ttsInit = TtsInit()
        ttsInit.init(context, mSpeechSynthesizer, this)
    }


    fun speak(msg: String, id: String? = null) {
        mSpeechSynthesizer.speak(msg, id)
    }

    fun synthesize(id: String, msg: String, listener: SynthesizeListener) {
        syntheMap[id] = listener
        mSpeechSynthesizer.synthesize(msg, id)
    }

    fun removeSynthsizeListener(id: String) = syntheMap.remove(id)

    override fun onError(p0: String?, p1: SpeechError?) {
        SpeechBus.post(SpeakEvent(SpeakEvent.CODE_ERROR, error = p1))
    }

    override fun onSpeechFinish(p0: String?) {
        SpeechBus.post(SpeakEvent(SpeakEvent.CODE_FINISH, p0 ?: "播放结束"))
    }

    override fun onSpeechProgressChanged(p0: String?, p1: Int) {
        SpeechBus.post(SpeakEvent(SpeakEvent.CODE_PROGRESS, p0 ?: "播放中", progress = p1))
    }

    override fun onSpeechStart(p0: String?) {
        SpeechBus.post(SpeakEvent(SpeakEvent.CODE_START, p0 ?: "开始播放"))
    }

    /**
     * 这个是获取到数据的回调
     * 音频数据
     */
    override fun onSynthesizeDataArrived(id: String?, data: ByteArray, progress: Int) {
        if (id.isNullOrBlank()) return
        val listener = syntheMap[id] ?: return
        listener.onSynthesizeDataArrived(id!!, data, progress)
    }

    /**
     * 结束后清楚
     */
    override fun onSynthesizeFinish(id: String?) {
        if (id.isNullOrBlank()) return
        val listener = syntheMap[id] ?: return
        listener.onSynthesizeFinish(id!!)
        syntheMap.remove(id)
    }

    override fun onSynthesizeStart(id: String?) {
        if (id.isNullOrBlank()) return
        val listener = syntheMap[id] ?: return
        listener.onSynthesizeStart(id!!)
    }

    fun release() {
        mSpeechSynthesizer.release()
    }

}